from django.shortcuts import render
import logging
# Create your views here.
from django.views import View
from apps.users.models import User
from django.http.response import JsonResponse, HttpResponse


class UserCountView(View):

    def get(self, request, username):
        count = User.objects.filter(username=username).count()

        return JsonResponse({'count': count})


class MobileView(View):
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        return JsonResponse({'count': count})


class RegisterView(View):

    def post(self, request):
        data_bytes = request.body
        str_data = data_bytes.decode()
        import json
        data = json.loads(str_data)

        username = data.get('username')
        password = data.get('password')
        password2 = data.get('password2')
        mobile = data.get('mobile')
        allow = data.get('allow')

        if not all([username, password2, password, mobile, allow]):
            return JsonResponse({'code': 400, 'msg': '必须字段不能为空'})

        import re
        if not re.match('[0-9a-zA-Z_]{8,20}', password):
            return JsonResponse({'code': 400, 'msg': '密码格式不对'})

        if password != password2:
            return JsonResponse({'code': 400, 'msg': '两次密码不一致'})

        if not re.match('1[3-9]\d{9}', mobile):
            return JsonResponse({'code': 400, 'msg': '手机号格式不挣正确'})

        user = User.objects.create_user(
            username=username,
            password=password,
            mobile=mobile
        )

        from django.contrib.auth import login
        login(request, user)

        return JsonResponse({'code': 0})


class LoginView(View):
    def post(self, request):
        import json
        # 1. 接收参数
        data = json.loads(request.body.decode())
        # 2. 提取参数
        username = data.get('username')
        password = data.get('password')
        remembered = data.get('remembered')
        import re
        # 判断，如果为手机号，则username_field =mobile，否则为username
        if re.match('1[3-9]\d{9}', username):
            User.USERNAME_FIELD = 'mobile'
        else:
            User.USERNAME_FIELD = 'username'

        # 3. 验证参数
        if not all([username, password]):
            return JsonResponse({'code': 400, 'errmsg': '参数不全'})

        from django.contrib.auth import authenticate

        user = authenticate(username=username, password=password)

        if user is None:
            return JsonResponse({'code': 400, 'errmsg': '用户名或密码不正确'})

        # 5. 状态保持
        from django.contrib.auth import login
        login(request, user)

        response = JsonResponse({'code': 0, 'errmsg': 'ok'})

        if remembered:
            # 默认是两周
            request.session.set_expiry(None)
            # 如果用手机号登录用户名那显示手机号就是没用user.username
            response.set_cookie('username', user.username, max_age=14 * 24 * 3600)
            print('111%s' % username)
        else:
            # 浏览器关闭的时候结束
            request.session.set_expiry(0)
            response.set_cookie('username', user.username)
            print(username)

        return response


class LogoutView(View):
    def delete(self, request):
        from django.contrib.auth import logout
        logout(request)

        response = JsonResponse({'code': 0, 'errmsg': 'ok'})

        response.delete_cookie('username')

        return response


from utils.views import LoginRequiredJSONMixin


class UserCenterView(LoginRequiredJSONMixin, View):
    def get(self, request):
        user = request.user

        # 组织json数据
        info_data = {
            'username': user.username,
            'mobile': user.mobile,
            'email': user.email,
            'email_active': user.email_active
        }
        # 返回响应
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'info_data': info_data})


from utils.views import LoginRequiredJSONMixin


class EmailView(LoginRequiredJSONMixin, View):
    def put(self, request):
        # 必须是登录用户
        # 1.获取请求数据
        import json
        data = json.loads(request.body.decode())
        # 2.提取参数
        email = data.get('email')
        # 3验证参数
        import re
        if not re.match('[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}', email):
            return JsonResponse({'code': 400, 'errmsg': '邮箱格式不正确'})
        # 4.更新数据
        request.user.email = email
        request.user.save()

        # 缺少的一个步骤 就是发送邮件!!!
        from django.core.mail import send_mail
        # subject, message, from_email, recipient_list,

        # # subject,      主题
        # subject = '美多商城激活邮件'
        # # message,      消息 内容
        # message = 'aaa'        #如果使用 html_message message为一个空字符串就可以
        # # from_email,   发件人
        # from_email = '美多商城官方邮箱<rileyle@163.com>'
        #
        # # recipient_list,  收件人列表
        # recipient_list = [email]
        #
        # html_message = '<a href="#">约吗?房间已开好,欢乐豆也买了</a>'
        #
        # send_mail(subject,
        #           message,
        #           from_email,
        #           recipient_list
        #          )
        from apps.users.common import generic_email_token
        token = generic_email_token(email, request.user.id)

        verify_url = 'http://www.meiduo.site:8080/success_verify_email.html?token=%s' % token
        from celery_meiduo.email.tasks import celery_send_mall
        # Todo delay
        celery_send_mall.delay(email, verify_url)
        # 5.返回响应

        return JsonResponse({'code': 0})


class EmailVerificationView(View):
    def put(self, reuqest):
        # 1. 接收请求
        data = reuqest.GET
        # 2. 提取数据
        token = data.get('token')
        if token is None:
            return JsonResponse({'code': 400, 'errmsg': '错误'})
        # 3. 对数据进行解密操作
        from apps.users.common import check_meail_token
        data = check_meail_token(token)
        # 4. 判断有没有user_id
        # 5. 如果没有则说明 token过期了
        if data is None:
            return JsonResponse({'code': 400, 'errmsg': 'token过期了'})
        email = data.get('email')
        user_id = data.get('user_id')
        # 6. 如果有,则查询用户信息
        try:
            user = User.objects.get(email=email, id=user_id)
        except User.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': '没有该用户'})

        # 7. 改变用户的邮箱激活状态
        user.email_active = True
        user.save()
        # 8. 返回响应
        return JsonResponse({'code': 0, 'errmsg': 'ok'})


"""

增删改查

web 
    请求 
        业务逻辑[增删改查] 
    响应


增
    1. 接收参数
    2. 提取参数
    3. 验证参数
    4. 数据入库
    5. 返回响应   
删
    1. 获取要删除数据id  指定删除某一[n]条数据   [id指定哪些数据]
    2. 根据id查询数据
    3. 删除数据[物理删除/逻辑删除]
    4. 返回响应
改
    1. 获取要更新[修改]数据id  指定修改某一[n]条数据   [id指定哪些数据]
    2. 根据id查询数据
    3. 接收参数
    4. 提取参数
    5. 验证参数
    6. 数据更新
    7. 返回响应   
查
    1.根据需求查询数据
    2.将对象转换为字典数据
    3.返回响应
"""
import json
from apps.users.models import Address


class CreateAddressView(View):
    def post(self, request):
        user = request.user
        count = Address.objects.filter(user=user, is_deleted=False).count()

        if count >= 20:
            return JsonResponse({'code': 0, 'errmsg': '新增地址超过上限'})

        # 1. 接收参数
        json_data = json.loads(request.body.decode())
        # 2. 提取参数
        receiver = json_data.get('receiver')
        province_id = json_data.get('province_id')
        city_id = json_data.get('city_id')
        district_id = json_data.get('district_id')
        place = json_data.get('place')
        mobile = json_data.get('mobile')
        tel = json_data.get('tel')
        email = json_data.get('email')
        # 3. 验证参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400, 'errmsg': '参数缺少'})

        # 4. 数据入库
        address = Address.objects.create(
            user=request.user,
            title=receiver,
            receiver=receiver,
            province_id=province_id,
            city_id=city_id,
            district_id=district_id,
            place=place,
            mobile=mobile,
            tel=tel,
            email=email
        )

        if user.default_address is None:
            user.default_address = address
            user.save()

        address_dict = {
            'id': address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        # 5. 返回响应
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'address': address_dict})


class AddressListView(LoginRequiredJSONMixin, View):
    def get(self, request):
        addresses = Address.objects.filter(user=request.user, is_deleted=False)

        addresses_list = []
        for address in addresses:
            addresses_list.append({
                'id': address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            })

        return JsonResponse({'code': 0, 'errmsg': 'ok', 'addresses': addresses_list,
                             'default_address_id': request.user.default_address_id})


import re


class UpdateDestroyAddressView(LoginRequiredJSONMixin, View):
    """修改地址"""

    def put(self, request, address_id):
        # 1. 接收参数
        json_dict = json.loads(request.body.decode())
        # 2. 提取参数
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 3. 验证参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400,
                                 'errmsg': '缺少必传参数'})

        if not re.match('1[3-9]\d{9}', mobile):
            return JsonResponse({'code': 400,
                                 'errmsg': '参数mobile有误'})
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse({'code': 400,
                                     'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code': 400,
                                     'errmsg': '参数email有误'})

        try:
            Address.objects.update(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
        except Exception as e:

            return JsonResponse({'code': 400, 'errmsg': '更新地址失败'})

        # 这儿是查询结果集，需要返回字典数据
        address = Address.objects.get(id=address_id)

        # 转换字典数据
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        # 响应更新地址结果
        return JsonResponse({'code': 0, 'errmsg': '更新地址成功', 'address': address_dict})

    def delete(self, request, address_id):
        """删除地址"""
        # 1.接收要删除的id
        try:
            address = Address.objects.get(id=address_id)
            address.is_deleted = True
            address.save()
        except Address.DoesNotExist:

            return JsonResponse({'code': 400, 'errmsg': '删除地址失败'})

        return JsonResponse({'code': 0, 'errmsg': '删除地址成功'})


class DefaultAddressView(View):
    def put(self, request, address_id):
        try:
            address = Address.objects.get(id=address_id)
            request.user.default_address = address
            request.user.save()
        except Exception as e:

            return JsonResponse({'code': 400, 'errmsg': '设置默认地址失败'})

        # 响应设置默认地址结果
        return JsonResponse({'code': 0, 'errmsg': '设置默认地址成功'})


class AddressTitleView(LoginRequiredJSONMixin, View):
    def put(self, request, address_id):
        # 1. 接收数据
        json_dict = json.loads(request.body.decode())

        # 2. 提取数据
        title = json_dict.get('title')

        try:
            address = Address.objects.get(id=address_id)
            address.title = title
            address.save()
        except Address.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': '设置地址标题失败'})

        # 4.响应删除地址结果
        return JsonResponse({'code': 0, 'errmsg': '设置地址标题成功'})


from django.contrib.auth import logout


class UpdatePwdView(LoginRequiredJSONMixin, View):
    def put(self, request):
        # 1. 接收数据
        json_dict = json.loads(request.body.decode())

        # 2. 提取数据
        old_password = json_dict.get('old_password')
        new_password = json_dict.get('new_password')
        new_password2 = json_dict.get('new_password2')

        # 3. 验证参数
        if not all([old_password, new_password, new_password2]):
            return JsonResponse({'code': 400,
                                 'errmsg': '缺少必传参数'})

        result = request.user.check_password(old_password)
        if not result:
            return JsonResponse({'code': 400,
                                 'errmsg': '原始密码不正确'})

        if not re.match('[0-9a-zA-Z]{8,20}', new_password):
            return JsonResponse({'code': 400,
                                 'errmsg': '密码最少8位,最长20位'})

        if new_password2 != new_password:
            return JsonResponse({'code': 400,
                                 'errmsg': '两次输入密码不一致'})

        # 4.更新数据
        try:
            request.user.set_password(new_password)
            request.user.save()
        except Exception:
            return JsonResponse({'code': 400, 'errmsg': '更新失败'})

        # 清理状态保持信息
        logout(request)

        response = JsonResponse({'code': 0, 'errmsg': 'ok'})

        response.delete_cookie('username')

        return response


"""
http://doc.redisfans.com/

需求:
    添加浏览记录  -- redis    list

前端:
    登录用户,访问某一个SKU的时候,发送一个访问请求.携带 商品id

后端:

    请求:
                POST        browse_histories    sku_id 在body中
    业务逻辑:
            1. 接收请求
            2. 提取参数
            3. 验证参数
            4. 数据入库
                4.1 先去重
                4.2 再添加
                4.3 保证列表中有5条浏览记录
            5. 返回响应

    响应:
            code:0


"""
from apps.goods.models import SKU
from django_redis import get_redis_connection


class UserHistoryView(LoginRequiredJSONMixin,View):
    def post(self, request):
        user = request.user
        # 1. 接收请求
        json_dict = json.loads(request.body.decode())
        # 2. 提取参数
        sku_id = json_dict.get('sku_id')
        # 3. 验证参数
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': '没有此商品'})
        # 4. 数据入库
        #     4.1 先去重

        redis_cli = get_redis_connection('history')
        pipeline = redis_cli.pipeline()
        user_id = user.id
        pipeline.lrem(user_id, 0, sku_id)
        #     4.2 再添加
        pipeline.lpush(user_id, sku_id)
        #     4.3 保证列表中有5条浏览记录
        pipeline.ltrim(user.id, 0, 4)

        pipeline.execute()
        # 5. 返回响应
        return JsonResponse({'code': 0, 'errmsg': 'ok'})

    """
    1. 必须是登录用户
    2. 获取用户信息
    3. 连接redis
    4. 查询浏览记录 [1,2,3]
    5. 遍历列表数据,查询商品详细信息
    6. 将对象转换为字典数据
    7. 返回响应
    :param request:
    :return:
"""

    def get(self,request):
        # 1. 必须是登录用户
        # 2. 获取用户信息
        user = request.user
        # 3. 连接redis
        redis_conn = get_redis_connection('history')

        # 4. 查询浏览记录 [1,2,3]
        sku_ids=redis_conn.lrange(user.id,0,-1)
        # 5. 遍历列表数据,查询商品详细信息
        skus =[]
        for id in sku_ids:
            sku = SKU.objects.get(id =id)
            skus.append({
                'id':sku.id,
                'name':sku.name,
                'price':sku.price,
                'default_image_url':sku.default_image.url   # url 调用自定义存储类的url属性
            })

        # 6. 将对象转换为字典数据

        # 7. 返回响应
        return JsonResponse({'code': 0, 'skus': skus, 'errmsg': 'ok'})
        pass